package com.pay.paytoken.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.pay.paytoken.R;
import com.pay.paytoken.activity.lock.LockManager;
import com.pay.paytoken.base.BaseActivity;
import com.pay.paytoken.fragment.MainSettingFragment;
import com.pay.paytoken.fragment.MainTokenFragment;
import com.pay.paytoken.fragment.MainUserManagerFragment;
import com.pay.paytoken.listener.SettingFirstListener;

import java.util.ArrayList;
import java.util.List;

import apiUtils.apis.GetDataTimeAPI;
import appUtils.AppUtil;
import appUtils.FragmentDockUtil;
import appUtils.LogUtil;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.OnClick;
import constant.AppConstants;
import netWorkUtil.NetWorkChangeCallBack;
import netWorkUtil.NetWorkUtil;
import netWorkUtil.NetworkStateReceiver;
import totpUtils.SPUtils;

import static appUtils.SharedPreferencesManager.FIRST;
import static appUtils.SharedPreferencesManager.VERIFY_PHONE;
import static com.pay.paytoken.activity.WelcomeActivity.VERIFICATION;
import static totpUtils.config.MTokenConstants.PREFS_SERVICE_TIME_REDUCE;

public class MainActivity extends BaseActivity {
    private final List<Fragment> mMainFragments = new ArrayList<>();
    @Bind(R.id.activity_main_bottom_btn1)
    Button mBottomBtn1;
    @Bind(R.id.activity_main_bottom_btn2)
    Button mBottomBtn2;
    @Bind(R.id.activity_main_bottom_btn3)
    Button mBottomBtn3;
    @Bind(R.id.rg_radiogroup_homePage)
    RadioGroup mRadioGroup;
    private long mFirstTime = 0;
    private MainUserManagerFragment mMainUserManagerFragment;
    private FragmentDockUtil mFragmentDockUtil = null;

    @Override
    protected void onResume() {
        super.onResume();
        if (!AppConstants.timeRunning) {
            AppConstants.timeRunning = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetworkStateReceiver.getInstance().removeRegisterObserver();
    }

    @Override
    public int setView() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        controlFirst(mSharedPreferencesManager.readBoolean(FIRST, true));
        if (mMainFragments.size() < 1) {
            mMainFragments.add(new MainTokenFragment());
            mMainUserManagerFragment = initMainUserManagerFragment();
            mMainFragments.add(mMainUserManagerFragment);
            mMainFragments.add(new MainSettingFragment());
        }
        if (mFragmentDockUtil == null) {
            int index = (mSharedPreferencesManager.readBoolean(FIRST, true) ? 1 : 0);
            mFragmentDockUtil = new FragmentDockUtil(MainActivity.this, mMainFragments, index,
                    R.id.afl_framelayout_content, mRadioGroup);
        }
    }

    private void controlFirst(boolean flag) {
        mRadioGroup.getChildAt(0).setEnabled(!flag);
        mRadioGroup.getChildAt(1).setEnabled(!flag);
        mRadioGroup.getChildAt(2).setEnabled(!flag);
        mBottomBtn1.setVisibility(flag ? View.VISIBLE : View.GONE);
        mBottomBtn2.setVisibility(flag ? View.VISIBLE : View.GONE);
        mBottomBtn3.setVisibility(flag ? View.VISIBLE : View.GONE);
    }

    private MainUserManagerFragment initMainUserManagerFragment() {
        return new MainUserManagerFragment().setSettingChangeListener(new SettingFirstListener() {
            @Override
            public void settingFirst(boolean flag) {
                controlFirst(flag);
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (getIntent().getIntExtra(VERIFICATION, 0) == 1) {
            startActivity(new Intent(this, PasswordVerificationActivity.class));
        } else if (LockManager.getInstance().getLockAble()) {
            LockManager.getInstance().startLockActivity(this);
        }
        super.onCreate(savedInstanceState);
        if (!LockManager.getInstance().getLockAble() && !mSharedPreferencesManager.readBoolean(VERIFY_PHONE, true)) {
            LockManager.getInstance().setDigitalLock(this);
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (!LockManager.getInstance().getLockAble() && !mSharedPreferencesManager.readBoolean(VERIFY_PHONE, true)) {
            LockManager.getInstance().setDigitalLock(this);
        }
        NetworkStateReceiver.getInstance().registerObserver(this, new NetWorkChangeCallBack() {
            @Override
            public void connectionType(NetWorkUtil.NetType netType) {
                ToastUtil.showShort(R.string.switching_network_success);
            }

            @Override
            public void unknowToNet(NetWorkUtil.NetType netType) {
                ToastUtil.showShort(R.string.network_connect);
                correctTime();
            }

            @Override
            public void netToUnknow(NetWorkUtil.NetType netType) {
                ToastUtil.showShort(R.string.disconnecting_the_network_affects_the_accuracy_of_the_token);
            }
        });
    }

    /*防重影处理*/
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - mFirstTime > 2000) {
                ToastUtil.showLong(R.string.again_according_to_exit_program);
                mFirstTime = System.currentTimeMillis();
            } else {
                AppUtil.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != AppConstants.MAINACTIVITY_MSG_REQUEST) {
            LogUtil.log("MainActivity onActivityResult requestCode error");
            return;
        }
        switch (resultCode) {
            case AppConstants.BIND_MSG_RESULT:
                if (mRadioGroup.getChildCount() < 1) {
                    LogUtil.log("MainActivity RadioGroup count null");
                    return;
                }
                RadioButton radioButton = (RadioButton) mRadioGroup.getChildAt(0);
                radioButton.setChecked(true);
                mMainUserManagerFragment.doAfterBindSuccess();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    protected void correctTime() {
        new GetDataTimeAPI().getServerTime(new GetDataTimeAPI.Listener() {
            @Override
            public void onSuccess(long deltaTime) {
                SPUtils.put(PREFS_SERVICE_TIME_REDUCE, deltaTime);
            }

            @Override
            public void onFailure(int code) {
            }
        });
    }

    @OnClick({R.id.activity_main_bottom_btn1, R.id.activity_main_bottom_btn3})
    protected void clickBottomBtn() {
        ToastUtil.showShort(R.string.please_account_binding);
    }
}
